package utils;

import constants.session.Session;
import constants.system.MemberShip;
import duppentity.dto.sys.SysItemDto;
import play.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import play.Play;

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;




/**
 * @author yangzhi
 * @date 2019/2/22
 */
public class ToolsUtils {

	private static final int invalidAge = -1;//非法的年龄，用于处理异常。
	/**
	 *根据身份证号码计算年龄
	 * @param idNumber 考虑到了15位身份证，但不一定存在
	 */

	public static int getAgeByIDNumber(String idNumber) {
		String dateStr;
		if (idNumber.length() == 15) {
			dateStr = "19" + idNumber.substring(6, 12);
		} else if (idNumber.length() == 18) {
			dateStr = idNumber.substring(6, 14);
		} else {//默认是合法身份证号，但不排除有意外发生
			return invalidAge;
		}


		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
		try {
			Date birthday = simpleDateFormat.parse(dateStr);
			return getAgeByDate(birthday);
		} catch (ParseException e) {
			return invalidAge;
		}


	}

	/**
	 *根据生日计算年龄
	 * @param dateStr 这样格式的生日 1990-01-01
	 */

	public static int getAgeByDateString(String dateStr) {
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		try {
			Date birthday = simpleDateFormat.parse(dateStr);
			return getAgeByDate(birthday);
		} catch (ParseException e) {
			return -1;
		}
	}


	public static int getAgeByDate(Date birthday) {
		Calendar calendar = Calendar.getInstance();

		//calendar.before()有的点bug
		if (calendar.getTimeInMillis() - birthday.getTime() < 0L) {
			return invalidAge;
		}


		int yearNow = calendar.get(Calendar.YEAR);
		int monthNow = calendar.get(Calendar.MONTH);
		int dayOfMonthNow = calendar.get(Calendar.DAY_OF_MONTH);

		calendar.setTime(birthday);


		int yearBirthday = calendar.get(Calendar.YEAR);
		int monthBirthday = calendar.get(Calendar.MONTH);
		int dayOfMonthBirthday = calendar.get(Calendar.DAY_OF_MONTH);

		int age = yearNow - yearBirthday;


		if (monthNow <= monthBirthday && monthNow == monthBirthday && dayOfMonthNow < dayOfMonthBirthday || monthNow < monthBirthday) {
			age--;
		}

		return age;
	}

	public static final String  urlPar ="http://www.ip138.com/search.asp";

	/**
	 * 获得手机号码归属地
	 *
	 * @param mobileNumber
	 * @return
	 * @throws Exception
	 */
	public static String getMobileFrom(String mobileNumber) throws Exception {
		String result="";
		if(!Utils.isMobilephone(mobileNumber)){
			Logger.error("不是完整的11位手机号或者正确的手机号前七位"+mobileNumber);
			return  "";
		}

		try {
			String url =urlPar+"?mobile="+mobileNumber+"&action=mobile";
			Document document= Jsoup.connect(url).get();
			Elements texts =document.select("[class='tdc2']");
			result = texts.get(1).text();
			Logger.info("mobileNumber:"+mobileNumber+":"+result);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return result;

	}

	/**
	 * 测试
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {
		System.out.println(getMobileFrom("13242801072"));
	}


	/**
	 * 时间戳转字符串格式
	 *
	 * @param dt
	 */
	public static String dateFormat(Long dt) {
		if (dt == null) {
			return "";
		}

		SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return s.format(new Date(dt));
	}

	/**
	 * 检查列表具体按钮（功能点）是否有权限
	 * @param url
	 * @return
	 */
	public static Boolean checkBtn(String url){
		Boolean result = false;
		MemberShip memberShip = MemberShip.current();
		String userKey =  memberShip.getId().toString().concat("_userItemList");
		Session session = Session.current();
		List<SysItemDto> sysItemDtoList =(List<SysItemDto>)session.get(userKey);
		if (sysItemDtoList.size()>0) {
			for (Integer i=0;i<sysItemDtoList.size();i++) {
				if (sysItemDtoList.get(i).itemHref.equals(url)) {
					result = true;
					break;
				}
			}
		}
		return result;
	}

	public static Long getTimeValue(){
		return System.currentTimeMillis();
	}
}


